package edu.tsinghua.oxy.engineer.service.impl;

import edu.tsinghua.oxy.engineer.service.IProxyService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.annotation.PostConstruct;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.net.InetSocketAddress;
import java.net.Proxy;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;

/**
 * @author sean
 * @version 1.0
 * @date 2021/7/30
 */
@Service
@Slf4j
public class ProxyServiceImpl implements IProxyService {

    private List<Proxy> proxyList = new ArrayList<>();

    private Random r = new Random();

    /**
     * 列表中随机获取代理
     *
     * TODO 限制代理IP的使用频率
     * @return
     */
    @Override
    public Proxy getProxy() {
        return proxyList.get(r.nextInt(proxyList.size()));
    }

    /**
     * 启动时读取代理IP代理列表
     */
    @PostConstruct
    private void loadProxy() {
        try {
            String baseDir = System.getProperty("user.dir");
            BufferedReader reader = new BufferedReader(new FileReader(baseDir + File.separator + "proxyIp.txt"));

            String line = "";

            while ((line = reader.readLine()) != null) {
                String[] split = line.split(":");
                String ip = split[0];
                int port = new Integer(split[1]);
                Proxy proxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress(ip, port));
                proxyList.add(proxy);
            }
        } catch (Exception e) {
            log.error("加载代理出错 ", e);
        }
    }
}
